﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;

namespace XiuXiuTools
{
    public partial class ImportDataForm : XiuXiuTools.BaseForm
    {
        public ImportDataForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 开始导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImport_Click(object sender, EventArgs e)
        {
            var dt = new LightXiuCore.LightData.XIU_EMP_SCOREDataTable();
            var dlg = openFileDialog.ShowDialog();
            if (dlg == DialogResult.OK)
            {
                SetControlsEnable(this, false);
                backgroundCtl.RunWorkerAsync(openFileDialog.FileNames);
            }

        }

        private bool AddItemByFileName(LightXiuCore.LightData.XIU_EMP_SCOREDataTable dtScroe, LightXiuCore.LightData.XIU_EMPDataTable userDt, string fileName, string tjName)
        {
            int rowData = 0;
            int colData = 0;
            int selfData = 0;
            int allCout = 0;
            try
            {
                rowData = int.Parse(txtRowData.Text.Trim());
                colData = int.Parse(txtColData.Text);
                selfData = int.Parse(txtSelfData.Text.Trim());
                allCout = int.Parse(txtAllCount.Text.Trim());
            }
            catch
            {
                MessageBox.Show("参数类型错误");
                return false;
            }
            System.IO.FileInfo info = new System.IO.FileInfo(fileName);
            var scroeFrom = info.Name.ToUpper().Replace(".XLSX", "");
            scroeFrom = scroeFrom.Replace(".XLS", "");
            if (userDt.Count(wh => wh.EMP_NAME == scroeFrom) < 1)
            {
                userDt.AddXIU_EMPRow(Guid.NewGuid().ToString(), "未分类", scroeFrom, 1);
            }

            try
            {
                var bookScroe = NPOI.SS.UserModel.WorkbookFactory.Create(info.FullName);
                var rowName = bookScroe.GetSheetAt(0).GetRow(int.Parse(txtRowData.Text.Trim()) - 2);
                for (int i = rowData - 1; i < rowData + allCout; i++)
                {
                    var rowScore = bookScroe.GetSheetAt(0).GetRow(i);
                    var scoreString = rowScore.GetCell(colData - 1).StringCellValue;
                    if (rowScore == null)
                    {
                        continue;
                    }
                    int startCol = selfData - 1;
                    while ((rowName.GetCell(startCol) != null && rowName.GetCell(startCol).StringCellValue.Trim() != "") || (startCol + 1 == selfData))
                    {
                        var strDestName = rowName.GetCell(startCol).StringCellValue.Trim();
                        if ((selfData - 1) == startCol)
                        {
                            strDestName = scroeFrom;
                        }
                        try
                        {
                            AddDataToTable(dtScroe, scroeFrom, strDestName, scoreString, rowScore.GetCell(startCol).NumericCellValue, tjName);
                        }
                        catch
                        {
                            AddDataToTable(dtScroe, scroeFrom, strDestName, scoreString, 0, tjName);
                        }
                        startCol++;
                    }
                }
            }
            catch (NPOI.EncryptedDocumentException)
            {
                MessageBox.Show(fileName + "设置了密码请先解除密码.没有被加载。");
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }



        private void AddDataToTable(LightXiuCore.LightData.XIU_EMP_SCOREDataTable dtScroe, string userName, string destUserName, string scortType, double score, string tjName)
        {
            var row = dtScroe.Where(wh => wh.SCROE_OWNER_EMP_NAME == destUserName && wh.SCROE_EMP_NAME == userName && wh.SCROE_TYPE == scortType);
            if (row.Count() < 1)
            {
                dtScroe.AddXIU_EMP_SCORERow(Guid.NewGuid().ToString(), destUserName, userName, scortType, (decimal)score, tjName);
            }
            else
            {
                if ((decimal)score > row.First().SCROE_VALUE)
                {
                    row.First().SCROE_VALUE = (decimal)score;
                }
            }
        }

        /// <summary>
        /// 开始后台处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundCtl_DoWork(object sender, DoWorkEventArgs e)
        {
            var fileNames = e.Argument as string[];
            var dtScroe = new LightXiuCore.LightData.XIU_EMP_SCOREDataTable();
            var dtUser = new LightXiuCore.LightData.XIU_EMPDataTable();

            foreach (string file in fileNames)
            {
                AddItemByFileName(dtScroe, dtUser, file, txtTjName.Text);
            }

            var dtusers = serviceClient.GetDataBySql("SELECT * FROM zjwdb_165769.xiu_emp;", "users");


            foreach (DataRow user in dtusers.Rows)
            {
                var row = dtUser.FirstOrDefault(wh => wh.EMP_NAME == user["EMP_NAME"].ToString());
                if (row != null)
                {
                    row.Delete();
                }
            }
            serviceClient.UpdateData(dtScroe, "SELECT * FROM zjwdb_165769.xiu_emp_score where 1=2 ; ", "DELETE  FROM zjwdb_165769.xiu_emp_score WHERE SCROE_TIME='" + txtTjName.Text + "'");
            serviceClient.UpdateData(dtUser, "SELECT * FROM zjwdb_165769.xiu_emp where 1=2 ;", "");


        }

        /// <summary>
        /// 后台处理完成操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundCtl_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            SetControlsEnable(this, true);
        }
        /// <summary>
        /// 用户类别列表
        /// </summary>
        DataTable UserTypeList = new DataTable();
        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImportDataForm_Load(object sender, EventArgs e)
        {
            SetControlsEnable(this, false);

            backLoadData.RunWorkerAsync("load");
            cmbUserType.SelectedIndexChanged += new EventHandler(cmbUserType_SelectedIndexChanged);
        }
        /// <summary>
        /// 保存设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            SetControlsEnable(this, false);
            backLoadData.RunWorkerAsync("saveconfig");
        }

        /// <summary>
        /// 用户类别选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbUserType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var obj = (cmbUserType.SelectedItem as DataRowView).Row;
            if (obj != null)
            {
                txtRowData.Text = obj["T_START_ROW"].ToString();
                txtRowData.Tag = "T_START_ROW";
                txtColData.Text = obj["T_START_COL"].ToString();
                txtColData.Tag = "T_START_COL";
                txtAllCount.Text = obj["T_START_COUNT"].ToString();
                txtAllCount.Tag = "T_START_COUNT";
                txtSelfData.Text = obj["T_START_SELF"].ToString();
                txtSelfData.Tag = "T_START_SELF";
            }
        }

        /// <summary>
        /// 后台查询数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backLoadData_DoWork(object sender, DoWorkEventArgs e)
        {

            var arg = e.Argument as string;
            if (arg != null)
            {
                if (arg == "load")
                {
                    UserTypeList = serviceClient.GetDataBySql("SELECT * FROM zjwdb_165769.xiu_emp_type;", "userType");

                }
                if (arg == "saveconfig")
                {
                    serviceClient.UpdateData(cmbUserType.DataSource as DataTable, "SELECT * FROM zjwdb_165769.xiu_emp_type where 1=2 ;", "");

                }
            }



        }

        /// <summary>
        /// 查询数据完成后绑定数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backLoadData_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            cmbUserType.DataSource = UserTypeList;
            SetControlsEnable(this, true);
        }

        /// <summary>
        /// 文本改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtRowData_TextChanged(object sender, EventArgs e)
        {
            var sd = sender as TextBox;
            var obj = (cmbUserType.SelectedItem as DataRowView).Row;
            if (obj != null)
            {
                obj[sd.Tag.ToString()] = sd.Text;
            }
        }


    }
}
